using UniversalAdminSystem.Application.AIQuestions.DTOs;
using UniversalAdminSystem.Application.AIQuestions.Interfaces;
using UniversalAdminSystem.Application.Common.Interfaces;
using UniversalAdminSystem.Application.PermissionManagement.Interfaces;
using UniversalAdminSystem.Domian.Core.ValueObjects;
using UniversalAdminSystem.Domian.UserConversations.Aggregates;
using UniversalAdminSystem.Domian.UserConversations.IRepository;
using UniversalAdminSystem.Domian.UserManagement.IRepository;

namespace UniversalAdminSystem.Application.AIQuestions.Service;

public class AIQusetionsAppService : IAIQusetionsAppService
{
    private readonly IMessageRepository _messageRepo;

    private readonly IConversationsRepository _conversationsRepo;

    private readonly IPermissionCheckService _permissioncheck;

    private readonly IUserRepository _userRepository;

    private readonly IUnitOfWork _work;
    private readonly IAnswerService _answerService;

    public AIQusetionsAppService(IMessageRepository message,
                    IConversationsRepository conversations,
                    IPermissionCheckService permissioncheck,
                    IUnitOfWork work,
                    IUserRepository userRepository,
                    IAnswerService answerService)
    {
        _messageRepo = message;
        _conversationsRepo = conversations;
        _permissioncheck = permissioncheck;
        _work = work;
        _userRepository = userRepository;
        _answerService = answerService;
    }

    public async Task<ConversationsResultDto> CreateConversation(ConversationsDto conversationsDto)
    {
        try
        {
            var user = await _userRepository.GetByGuidAsync(conversationsDto.UserId) ?? throw new Exception("用户不存在");
            await _work.BeginTransactionAsync();
            var Conversation = Conversations.Create(conversationsDto.UserId, conversationsDto.Title);
            var entity = await _conversationsRepo.AddAsync(Conversation);
            await _work.CommitAsync();
            return new ConversationsResultDto(entity.Id.Value, entity.Title);
        }
        catch (System.Exception e)
        {
            await _work.RollbackAsync();
            throw new Exception($"用户会话创建失败:{e.Message}");
        }
    }

    public async Task DeleteUserConversations(Guid ConversationsId)
    {
        try
        {
            await _work.BeginTransactionAsync();
            await _messageRepo.RemoveByConversationIdAsync(ConversationsId);
            await _conversationsRepo.RemoveConversation(ConversationsId);
            await _work.CommitAsync();
        }
        catch (System.Exception)
        {
            await _work.RollbackAsync();
            throw new Exception("删除异常");
        }
    }

    public async Task<IEnumerable<ContentResultDto>> GetConversationMessage(Guid Id)
    {
        try
        {
            var list = await _messageRepo.GetByConversationIdAsync(Id);
            return list.Select(m => new ContentResultDto(m.Role, m.Content));
        }
        catch (System.Exception)
        {
            throw new Exception("获取用户会话消息失败");
        }
    }

    public async Task<IEnumerable<ConversationsResultDto>> GetUsersConversationsByUserId(Guid userId)
    {
        try
        {
            var user = await _userRepository.GetByGuidAsync(userId) ?? throw new Exception("用户不存在");
            var list = await _conversationsRepo.GetByUserIdAsync(userId);
            return list.Select(m => new ConversationsResultDto(m.Id.Value, m.Title));
        }
        catch (System.Exception e)
        {
            throw new Exception($"获取用户会话失败:{e.Message}");
        }
    }

    public async Task<string> Chat(Guid conversationId, string userInput)
    {
        try
        {
            // 开启事务
            await _work.BeginTransactionAsync();

            // 创建消息并持久化
            var message = Message.Create(ConversationId.Create(conversationId), "user", userInput);
            await _messageRepo.AddAsync(message);

            await _work.CommitAsync();
            // 回答
            await _work.BeginTransactionAsync();
            var messages = await _messageRepo.GetByConversationIdAsync(conversationId);
            System.Console.WriteLine("消息列表:",messages);
            var temp = await _answerService.AnswerAsync(userInput, messages);
            System.Console.WriteLine(temp);
            var Systemmessage =  Message.Create(ConversationId.Create(conversationId), "system", temp);
            await _messageRepo.AddAsync(Systemmessage);
            await _work.CommitAsync();
            return temp;
        }
        catch (System.Exception e)
        {
            await _work.RollbackAsync();
            throw new Exception(e.Message);
        }
        

    }

    public Task<ContentResultDto> UserAccess(Guid id, ContentDto content)
    {
        throw new NotImplementedException();
    }

    public Task<ContentResultDto> VisitorAccess(ContentDto content)
    {
        throw new NotImplementedException();
    }
}